<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Text Shuffle</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        font-size: 0;
        background-color: #333;
      }

      .container {
        padding: 20px 0;
        position: relative;
      }

      .container span {
        text-wrap: wrap;
        font-size: 24px;
      }
    </style>
  </head>
  <body>
    <div class="container" id="container">
      <span id="text-span">Hello World</span>
    </div>

    <script>
      // 获取文本容器和初始的 span
      const container = document.querySelector('#container');
      const textSpan = document.querySelector('#text-span');

      const shuffleText = (text) => {
        const charArray = text.split('');
        const newSpans = charArray.map((char) => {
          const span = document.createElement('span');
          span.textContent = char;
          return span;
        });

        // 2. 记录每个字符的位置
        const positions = newSpans.map((span) => {
          const rect = container.getBoundingClientRect();
          return {
            span,
            top: rect.top,
            left: rect.left,
          };
        });

        // 3. 打乱顺序
        const shuffledSpans = newSpans.sort(() => Math.random() - 0.5);

        // 4. 清空原始容器中的内容并添加打乱后的 span
        container.innerHTML = '';
        shuffledSpans.forEach((span) => container.appendChild(span));

        // 5. 使用绝对定位恢复原始顺序
        positions.forEach((pos, index) => {
          const span = pos.span;
          span.style.position = 'absolute';
          span.style.top = `${pos.top}px`;
          span.style.left = `${pos.left + index * 30}px`;
        });
      };

      shuffleText(textSpan.textContent);
    </script>
  </body>
</html>
